package com.farm.farming.controller;

import com.farm.entity.PageResult;
import com.farm.entity.Result;
import com.farm.entity.StatusCode;

import com.farm.farming.pojo.Customer;
import com.farm.farming.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RequestMapping("/customer")
@RestController
public class CustomerController {

    @Autowired
    private CustomerService customerService;


    @PostMapping("/add")
    public Result add(@RequestBody Customer customer){
        boolean flag=false;
        String regex = "[0-9]{11}$";
        Pattern check = Pattern.compile(regex);
        Matcher matcher = check.matcher(customer.getPhone());
        flag = matcher.matches();
        //手机号码的校验
        if (!flag){
            throw new RuntimeException("手机号码不正确");
        }

        try {
            customerService.add(customer);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,StatusCode.ERROR,"添加失败");
        }
        return new Result(true, StatusCode.OK,"添加完成");
    }

    @GetMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable("id")Integer id){

        try {
            customerService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,StatusCode.ERROR,"删除失败");
        }

        return new Result(true,StatusCode.OK,"删除完成");
    }

    @PostMapping("/update")
    public Result update(@RequestBody Customer customer){

        try {
            customerService.update(customer);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,StatusCode.ERROR,"修改失败");
        }
        return  new Result(true,StatusCode.OK,"修改完成");
    }


    @GetMapping("/findPage")
    public Result findPage( Customer customer,
                            @RequestParam(value = "page",defaultValue = "0",required = false) Integer currentPage,
                            @RequestParam(value = "size",defaultValue = "10",required = false) Integer size){

        PageResult<Customer> page = null;
        try {
            page = customerService.findPage(customer,currentPage,size);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,StatusCode.ERROR,"查询失败了");
        }

        return new Result(true,StatusCode.OK,"分页查询完成",page);
    }


}
